//========encoding:utf-8=========
/*
 * @describe:  三目运算符
 * @author:mhao
 * @copyright:chinasoft.cn
 * @date:2020年3月31日   下午5:49:45
 */
package edu.chinasoft.handler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import edu.chinasoft.domain.Application;
import edu.chinasoft.domain.PageUnitForApplication;
import edu.chinasoft.domain.Role;
import edu.chinasoft.domain.User;
import edu.chinasoft.service.ApplicationService;
import edu.chinasoft.util.Dom4jUtil;

@Controller("applicationHandler")
@RequestMapping("/applicationHandler")
public class ApplicationHandler {
	 private static Logger logger = LoggerFactory.getLogger(ApplicationHandler.class);
	 @Autowired
	 @Qualifier("applicationService")
	 private ApplicationService applicationService;
	 //填写请假单
	 @RequestMapping(value="/updateApplicationPage.do",method= {RequestMethod.POST,RequestMethod.GET})
	 public String addApplication(Application application,ModelAndView modelAndView, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
		 logger.info(" ApplicationHandler >>> addApplication start.......");
	     //获取用户填写的审批者
		 String approvaluser = request.getParameter("selectapprovaluser");
		 User approvalUser = new User();
		 approvalUser.setUserName(approvaluser);
		 application.setApplicationUser(approvalUser);
		 //获取当前时间
		 Date currentDate = new Date();
		 logger.info("当前时间为："+currentDate);
		 application.setOperationTime(currentDate);
		 logger.info("开始时间为："+application.getApplicationBegin());
		 logger.info("结束时间为："+application.getApplicationEnd());
		 //获取当前登录用户
		 User userLogin = (User)session.getAttribute("userLogin");
		 logger.info("当前登录用户为："+userLogin);
		 application.setApplicationUser(userLogin);
		 boolean result = applicationService.insertApplication(application);
		 if(!result) {
			 return "/addapplicationerror";
		 }
		 logger.info(" ApplicationHandler >>> addApplication end.......");
		 return "redirect:/applicationHandler/showNoSubmitApplication.do";
	 }
	 //提交请假单
	 @RequestMapping(value = "/showNoSubmitApplication.do",method = {RequestMethod.POST,RequestMethod.GET})
	 public ModelAndView showNoSubmitApplication(ModelAndView modelAndView, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        logger.info(" ApplicationHandler >>> showNoSubmitApplication start.......");
	        //获取分页单位
	        String initParameter = request.getServletContext().getInitParameter("pageUnit");
	        int pageUnit = Integer.parseInt(initParameter);
	        //获取当前页
	        String pageParameter = request.getParameter("currentPage");
	        pageParameter=pageParameter==null?"1":pageParameter;
	        int currentPage = Integer.parseInt(pageParameter);
	        //获取当前登录用户
	        User userLogin = (User) session.getAttribute("userLogin");
	        logger.info("当前登录用户为："+userLogin);
	        Map<String, Object> map = new HashMap<>();
	        int setLimit = (currentPage-1)*pageUnit;
	        map.put("setLimit",setLimit);
	        map.put("pageUnit",pageUnit);
	        map.put("userId",userLogin.getUserId());
	        logger.info("userId："+map.get("userId"));
	        //调用服务层方法
	        PageUnitForApplication pageUnitForApplication = applicationService.getNoSubmitApplicationRecordById(userLogin);
	        logger.info("总记录数为："+pageUnitForApplication.getRecordNum());
	        List<Application> applicationList = applicationService.selectNoSubmitApplicationById(map);
	        logger.info("applicationList："+applicationList);
	        //修改日期格式
	        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	        Map<Integer, Map> allTimeMap = new HashMap<Integer, Map>();
	        //所有申请记录的时间字典
	        for(Application application:applicationList) {
	        	 Map<String, String> applicationTimeMap = new HashMap<String, String>();
	        	 //每个申请记录的时间字典
	        	 Date applicationBeginDate = application.getApplicationBegin();
	             Date applicationEndDate = application.getApplicationEnd();
	             Date operationDate = application.getOperationTime();
	             String applicationBeginString = simpleDateFormat.format(applicationBeginDate);
	             String applicationEndString = simpleDateFormat.format(applicationEndDate);
	             String operationString = simpleDateFormat.format(operationDate);
	             logger.info(applicationBeginString+"："+applicationEndString+"："+operationString);
	             applicationTimeMap.put("applicationBeginString",applicationBeginString);
	             applicationTimeMap.put("applicationEndString",applicationEndString);
	             applicationTimeMap.put("operationString",operationString);
	             allTimeMap.put(application.getApplicationId(),applicationTimeMap);
	             logger.info("记录:"+allTimeMap.get(application.getApplicationId()));
	        }
	        logger.info("字典大小为："+allTimeMap.size());
	        Set<Integer> keySet = allTimeMap.keySet();
	        for (Integer key:keySet){
	            logger.info(key+"："+allTimeMap.get(key));
	        }
	        session.setAttribute("allTimeMap",allTimeMap);
	        pageUnitForApplication.setApplicationList(applicationList);
	        pageUnitForApplication.setPageUnit(pageUnit);
	        pageUnitForApplication.setCurrentPage(currentPage);
	        //加到session域里
	        session.setAttribute("nosubmitApplicationPage", pageUnitForApplication);
	        modelAndView.setViewName("/showNoSubmitApplication");
	        logger.info(" ApplicationHandler >>> showNoSubmitApplication end.......");
			return modelAndView;
	 }
	 //修改请假单
	 @RequestMapping(value="/updateApplicationPage.do",method= {RequestMethod.POST,RequestMethod.GET})
	 public ModelAndView getUserForAddApproval(Integer applicationId,String approvalName,ModelAndView modelAndView, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        logger.info(" ApplicationHandler >>> updateApplicationPage start.......");
	        logger.info("当前申请单的id为："+applicationId+"，审批者的名字为："+approvalName);
	        //获取当前用户的下一级审批者    获取当前登录用户
	        User userLogin = (User)session.getAttribute("userLogin");
	        //获取当前登录用户的角色
	        Role loginRole = applicationService.selectRoleByUser(userLogin);
	        //获取xml文件的绝对路径
	        String path="/config/flow.xml";
	        String realPath = request.getServletContext().getRealPath(path);
	        List<String> roleNameList = Dom4jUtil.getContent(realPath);
	        int index = roleNameList.indexOf(loginRole.getRoleName());
	        String roleName = roleNameList.get(index+1);
	        Role role = new Role();
	        role.setRoleName(roleName);
	        //获取角色对应的用户
	        List<User> userList = applicationService.selectUserByRole(role);
	        session.setAttribute("approvalUserInfo", userList);
	        logger.info("下一级审批者有："+userList);
	        Application application = new Application();
	        application.setApplicationId(applicationId);
	        //通过id获取当前申请单的其他信息
	        Application applicationById=applicationService.selectApplicationById(application);
	        logger.info("当前申请单的信息为："+applicationById);
	        User approvalUser = new User();
	        approvalUser.setUserName(approvalName);
	        applicationById.setApplicationUser(approvalUser);
	        session.setAttribute("updateapplication", applicationById);
	        modelAndView.setViewName("/updateapplication");
	        logger.info(" ApplicationHandler >>> updateApplicationPage end.......");
			return modelAndView;
	 }
	 @RequestMapping(value = "/deleteApplication.do",method = {RequestMethod.POST,RequestMethod.GET})
	    public String deleteApplication(Integer id,ModelAndView modelAndView, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        logger.info(" ApplicationHandler >>> deleteApplication start.......");
	        logger.info("当前申请单id为："+id);
	        Application application = new Application();
	        application.setApplicationId(id);
	        //调用服务层方法删除
	        boolean result = applicationService.deleteApplication(application);
	        if(!result) {
	        	return "/deleteapplicationerror";
	        }
	        logger.info(" ApplicationHandler >>> deleteApplication end.......");
			return "redirect:/applicationHandler/showNoSubmitApplication.do";
	 }
	 //查询待审核的请假单
	 @RequestMapping(value = "/showApprovalApplication.do",method = {RequestMethod.POST,RequestMethod.GET})
	 public ModelAndView showApprovalApplication(ModelAndView modelAndView,HttpSession httpSession,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws ServletException,IOException {
		 logger.info(" ApplicationHandler >>> showApprovalApplication start.......");
		 //获取分页单位
		
		 logger.info(" ApplicationHandler >>> showApprovalApplication end.......");
		return modelAndView;
	 }
	 @InitBinder
	 protected void initBinder(WebDataBinder binder) {
		 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 dateFormat.setLenient(false);
		 binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, false) );
	 }
}
